package com.example.pixelyear.view

import android.content.Context
import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.Rect
import android.util.AttributeSet
import android.view.View
import com.example.pixelyear.R
import com.example.pixelyear.utils.NumberUtils
import com.example.pixelyear.utils.UIUtils
import com.example.pixelyear.utils.Utils

class WeekView @JvmOverloads constructor(
    context: Context,
    attributes: AttributeSet? = null,
    defaultStyle: Int = 0
) :
    View(context, attributes, defaultStyle) {
    private var boxWidth = UIUtils.getDimension(R.dimen.dp_50) //宽度
    private var boxHeight = UIUtils.getDimension(R.dimen.dp_50) //高度
    private val boxPadding = 3 //分割线宽度
    private var textWeekHeight = 0
    private var textWeekWidth = 0
    private var rowSize = 7 //列数

    //星期文字画笔
    private val textWeekPaint by lazy {
        Paint().also {
            it.color = UIUtils.getColor(R.color.gray_666666)
            it.flags = Paint.ANTI_ALIAS_FLAG
            it.textSize = UIUtils.getDimensionFloat(R.dimen.sp_18)
        }
    }

    private val weekRect by lazy {
        Rect()
    }

    init {
        initTextWidth()
    }

    private fun initTextWidth() {
        textWeekPaint.getTextBounds("五", 0, "五".length, weekRect)
        textWeekHeight = weekRect.height()
        textWeekWidth = weekRect.width()
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        val widthMode = MeasureSpec.getMode(widthMeasureSpec)
        val heightMode = MeasureSpec.getMode(heightMeasureSpec)
        var w = 0
        var h = 0

        if (widthMode == MeasureSpec.AT_MOST || heightMode == MeasureSpec.UNSPECIFIED) {
            w = boxWidth * rowSize + boxPadding
        }

        if (heightMode == MeasureSpec.AT_MOST || heightMode == MeasureSpec.UNSPECIFIED) {
            //加一是加上星期行的高度
            h = boxHeight
        }
//        KLog.e("yxs", "高度宽度：" + w + "===" + h + " ===月份$month")
        setMeasuredDimension(w, h)
    }

    override fun onDraw(canvas: Canvas?) {
        super.onDraw(canvas)
        for (j in 0 until rowSize) {
            canvas?.drawText(
                NumberUtils.translateWeek(j + 1),
                (boxWidth * j).toFloat() + getTextRightPadding()
                ,
                boxHeight.toFloat() - getTextTopPadding(),
                textWeekPaint
            )
        }
    }


    private fun getTextTopPadding(): Float {
        return ((boxHeight - textWeekWidth) / 2).toFloat()
    }

    private fun getTextRightPadding(): Float {
        return ((boxWidth - textWeekWidth) / 2).toFloat()
    }

}
